package com.pc.admin.test.AddCoums;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class AddColumns {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/sgj_mdm";
        String user = "root";
        String password = "root";
        String tableName = "my_crud"; // 指定要处理的表名
        String[] columnsToAdd =
                {
                        "created_by  varchar(32) DEFAULT NULL COMMENT '创建人'",
                        "created_time date DEFAULT NULL COMMENT '创建时间'",
                        "updated_by varchar(32) DEFAULT NULL COMMENT '更新人'",
                        "updated_time date DEFAULT NULL COMMENT '更新时间'"
                };

        try (Connection connection = DriverManager.getConnection(url, user, password)) {
            DatabaseMetaData metaData = connection.getMetaData();
            for (String column : columnsToAdd) {
                try (ResultSet columns = metaData.getColumns(null, null, tableName, column.split(" ")[0])) {
                    if (!columns.next()) {
                        System.out.println("列 " + column.split(" ")[0] + " 不存在于表 " + tableName + "，添加列...");
                        try (Statement statement = connection.createStatement()) {
                            String sql = "ALTER TABLE " + tableName + " ADD COLUMN " + column;
                            statement.executeUpdate(sql);
                        }
                    } 
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}





